<?php

namespace app\admin\controller\task;

use app\common\controller\Backend;
use think\Db;

/**
 * 打款记录管理
 *
 * @icon fa fa-circle-o
 */
class RecordMoney extends Backend
{
    
    /**
     * Money模型对象
     * @var \app\common\model\record\Money
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\record\Money;
        $this->view->assign("payedList", $this->model->getPayedList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index(){
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $_where["a.payed"] = 1;
            //$_where["payed"] = 2;
            if(session('admin')['athur_id']==1) {
                $_where['t.shop_admin_id'] = session('admin')['athor'];
            }else{
                $_where['t.shop_admin_id'] = session('admin')['id'];
            }

            $join[] = ["sd_shop t","t.shop_id = a.shop_id","left"];
            $join[] = ["sd_shop_order","sd_shop_order.order_id = a.order_id","left"];
            $field = "a.record_id,a.order_id,a.username,a.bank_name,a.on_time,a.bank_no,a.record_id as id";
            $field .= ",sd_shop_order.order_id,sd_shop_order.tao_bao_order_no,sd_shop_order.order_sno,sd_shop_order.shop_name,sd_shop_order.tao_bao_no,sd_shop_order.real_money,sd_shop_order.create_time,sd_shop_order.status";

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->alias("a")
                ->join($join)
                ->where($where)
                ->where($_where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->alias("a")
                ->join($join)
                //->with('order')
                ->field($field)
                ->where($where)
                ->where($_where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();





            $list = collection($list)->toArray();


            foreach($list as &$value){

                $value["sd_shop_order.order_sno"] = $value["order_sno"];
                $value["sd_shop_order.shop_name"] = $value["shop_name"];
                $value["sd_shop_order.tao_bao_no"] = $value["tao_bao_no"];
                $value["sd_shop_order.tao_bao_order_no"] = $value["tao_bao_order_no"];
                $value["sd_shop_order.real_money"] = $value["real_money"];
                $value["sd_shop_order.create_time"] = $value["create_time"];
                $value["a.on_time"] = $value["on_time"];
                $value["sd_shop_order.status"] = $value["status"];

            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 打款成功（type：1）
     *
     * 失败注册（type：2）remark
     * @param string $ids
     * @return string
     */
    public function remarks($ids = '')
    {
        $row = $this->model->get(['record_id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row->payed == 2){
            $this->error('改笔订单已付款');
        }
        if($this->request->isPost()){

            $params = $this->request->post();

            if($params) {

                $order_info = Db::name("shop_order")->where("order_id", $params["order_id"])->find();//
                //halt($params);
                try {
                    $data = [];
                    if ($params["type"] == 1) {
                        $data["payed"] = 2;

                    } elseif ($params["type"] == 2) {
                        $data["fail_remarks"] = $params["fail_remarks"];
                    }

                    if ($order_info["order_state"] == 1) {
//                    renderJson("该订单已被撤销",0);
                        $this->error('该订单已被撤销');
                    }
                    //unset($params["ids"]);
                    //unset($params["type"]);

                    $this->model->where('record_id', $ids)->update($data);
                    if ($params["type"] == 1) {//打款成功
                        Db::name("shop_order")->where("order_id", $params["order_id"])->update(["payed" => "2", "status" => "5"]);//订单信息修改

                        $info = Db::name("record_money")->where('record_id', $ids)->find();

                        $uid = $order_info["uid"];
                        $openid = Db::name("wx_users")->where("uid", $uid)->value("openid");
                        $date = date("Y-m-d", time());
                        $day = date("H:i:s", time());
                        $flag = $info["bank_name"] . "-" . $info["bank_no"] . "-" . $info["cash"] . "元";
                        $content = [
                            $date, $day, $flag
                        ];
                        $msg = [
                            "condition" => 12,
                            "touser" => $openid,
                            "content" => $content
                        ];
                        $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                        $MiniMsg->sendMsg();//发送短信模板打款成功
                    }
                    $this->success('审核通过');
                } catch (Exception $e) {
                    $this->error('审核失败');
                }
            }
        }
        $this->view->assign("type", input("type"));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 打款成功
     */
    public function remarks_success($ids = ''){
        $row = $this->model->get(['record_id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row->payed == 2){
            $this->error('改笔订单已付款');
        }
        if($this->request->isPost()){

            $params = $this->request->post();

            if($params) {
                $this->remarks_act($ids,$params);
            }
        }
        $this->view->assign("type", input("type"));
        $this->view->assign("row", $row);
        return $this->view->fetch("remarks");
    }


    /**
     * 失败注册
     */
    public function remarks_fail($ids = ''){
        $row = $this->model->get(['record_id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row->payed == 2){
            $this->error('改笔订单已付款');
        }
        if($this->request->isPost()){

            $params = $this->request->post();

            if($params) {
                $this->remarks_act($ids,$params);
            }
        }
        $this->view->assign("type", input("type"));
        $this->view->assign("row", $row);
        return $this->view->fetch("remarks");
    }


    /**
     * 批量打款成功
     */
    public function payed(){

        $pass = input("post.");

        $ids = [];//打款记录id
        $order_ids = [];//批量订单id

        $count = 0;

        foreach ($pass["ids"] as $k=>$v){
            if($v["payed"]==1 && $v["order"]["order_state"]!=1) {
                $ids[] = $v["record_id"];
                $order_ids[] = $v["order_id"];
                $openid = Db::name("wx_users")->where("uid",$v["uid"])->value("openid");
                $date   = date("Y-m-d",time());
                $day    = date("H:i:s",time());
                $flag   = $v["bank_name"]."-".$v["bank_no"]."-".$v["cash"]."元";
                $content = [
                    $date,$day,$flag
                ];
                $count++;
                $msg = [
                    "condition"=>12,
                    "touser"=>$openid,
                    "content"=>$content
                ];
                $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                $MiniMsg->sendMsg();//发送短信模板打款成功
            }
        }

        try{

        Db::name("record_money")->where("record_id","in",$ids)->update(["payed"=>2]);//p

        Db::name("shop_order")->where("order_id","in",$order_ids)->update(["status"=>5,"payed"=>2]);

        }catch (\Exception $e){

            renderJson($e->getMessage(),0);

        }
        if($count) {
            renderJson("批量打款成功", 1);
        }else{
            renderJson("未找到适合选项", 0);
        }


    }


    /**
     * 汇款导出
     */
    public function export_act(){

        $admin = session('admin');
        $group_info =  model('AuthGroupAccess')->where('uid',$admin['id'])->find();
        $rules_t = model('AuthGroup')->where('id',$group_info['group_id'])->value("rules");
        $rules = explode(",",$rules_t);
        if($rules_t!='*') {
            $rule_name = model('AuthRule')->where('id', 'in', $rules)->column("name");
            if (!in_array('task/recordmoney/export_act', $rule_name)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($this->request->isGet()) {
            $params = $this->request->get();
            if ($params)
            {
                //halt($params);
                if($params["ids"]){//批量发送
                    $params["ids"] = (string)$params["ids"];
                    $ids = explode(",",$params["ids"]);

                    $join[] = ["sd_shop_order r","r.order_id = d.order_id","left"];

                    $record_money_list = Db::name("record_money")->alias("d")->join($join)->where("d.record_id","in",$ids)->field("d.*,r.real_money")->select();

                    $data = [];
                    //获取所有的金额
                    foreach ($record_money_list as $key=>$value){
                        $data[$key]["username"] = $value["username"];//用户名
                        $data[$key]["bank_no"] = $value["bank_no"]." ";//卡号
                        $data[$key]["bank_name"] = $value["bank_name"];//名称
                        $data[$key]["cash"] = $value["real_money"];//现金
                        $data[$key]["on_time"] = date("Y-m-d H:i:s",$value["on_time"]);//创建时间
                    }

                    /**
                     * 数据导出
                     * @param array $title   标题行名称
                     * @param array $data   导出数据
                     * @param string $fileName 文件名
                     * @param string $savePath 保存路径
                     * @param $type   是否下载  false--保存   true--下载
                     * @return string   返回文件全路径
                     * @throws PHPExcel_Exception
                     * @throws PHPExcel_Reader_Exception
                     */
                    $this->export(["用户名","卡号","名称","现金","创建时间"],$data,'刷单','./',true);

                }


            }
        }

    }


    /**
     *打款和失败注册的公用类型
     */
    public function remarks_act($ids,$params){
        $order_info = Db::name("shop_order")->where("order_id", $params["order_id"])->find();//
        //halt($params);
        try {
            $data = [];
            if ($params["type"] == 1) {
                $data["payed"] = 2;

            } elseif ($params["type"] == 2) {
                $data["fail_remarks"] = $params["fail_remarks"];
            }

            if ($order_info["order_state"] == 1) {
//                    renderJson("该订单已被撤销",0);
                $this->error('该订单已被撤销');
            }
            //unset($params["ids"]);
            //unset($params["type"]);

            $this->model->where('record_id', $ids)->update($data);
            if ($params["type"] == 1) {//打款成功
                Db::name("shop_order")->where("order_id", $params["order_id"])->update(["payed" => "2", "status" => "5"]);//订单信息修改

                $info = Db::name("record_money")->where('record_id', $ids)->find();

                $uid = $order_info["uid"];
                $openid = Db::name("wx_users")->where("uid", $uid)->value("openid");
                $date = date("Y-m-d", time());
                $day = date("H:i:s", time());
                $flag = $info["bank_name"] . "-" . $info["bank_no"] . "-" . $info["cash"] . "元";
                $content = [
                    $date, $day, $flag
                ];
                $msg = [
                    "condition" => 12,
                    "touser" => $openid,
                    "content" => $content
                ];
                $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                $MiniMsg->sendMsg();//发送短信模板打款成功
            }
            $this->success('审核通过');
        } catch (Exception $e) {
            $this->error('审核失败');
        }
    }


}
